package com.sz.admin.system.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sz.admin.system.mapper.SysUserRoleMapper;
import com.sz.admin.system.pojo.dto.sysmenu.SysUserRoleDTO;
import com.sz.admin.system.pojo.po.SysUserDept;
import com.sz.admin.system.pojo.po.SysUserRole;
import com.sz.admin.system.pojo.vo.sysrole.SysRoleVO;
import com.sz.admin.system.service.SysUserRoleService;
import com.sz.admin.vehicleinfo.pojo.dto.VehicleInfoListDTO;
import com.sz.admin.vehicleinfo.pojo.vo.VehicleInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.sz.admin.system.pojo.po.table.SysUserRoleTableDef.SYS_USER_ROLE;

/**
 * <p>
 * 系统用户-角色关联表 服务实现类
 * </p>
 *
 * @author sz
 * @since 2022-10-01
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    /**
     * 获取用户的角色
     * 
     * @param userId
     *            用户id
     * @return 用户角色集合
     */
    @Override
    public List<String> getUserRolesByUserId(Long userId) {
        QueryWrapper queryWrapper = QueryWrapper.create().select(SYS_USER_ROLE.ROLE_ID).from(SYS_USER_ROLE).where(SYS_USER_ROLE.USER_ID.eq(userId));
        return listAs(queryWrapper, String.class);
    }

    @Override
    public void syncUserRole(Long userId, Long roleId) {
        QueryWrapper wrapper = QueryWrapper.create().eq(SysUserRole::getRoleId, userId);
        remove(wrapper); // 清除旧的信息
        List<SysUserRole> users = new ArrayList<>();
        //for (Long userId : userIds) {
        SysUserRole userR = new SysUserRole();
        userR.setRoleId(roleId);
        userR.setUserId(userId);
        users.add(userR);
        //}
        saveBatch(users); // 批量生成新的信息
    }
    @Override
    public void syncUserRolec(Long userId, Long roleId) {
        // 根据userId清除用户的现有角色关联
        QueryWrapper wrapper = QueryWrapper.create().eq(SysUserRole::getUserId, userId);
        remove(wrapper);
        
        // 为用户设置新的角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        save(userRole);
    }



}